﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using MyLib;
using System.Data;

namespace Portal
{
    public partial class SelectDept : System.Web.UI.Page
    {
        StringBuilder StrSQL = null;
        string rtnJson = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.txtType.Text = Request.QueryString["Type"];
                BingDepartments();
            }
        }
        private string getDeptName(string name)
        {
            if (!String.IsNullOrEmpty(name))
            {
                int index = name.IndexOf('[');
                if (index > 0)
                {
                    return name.Substring(0, index);
                }
                else
                {
                    return name;
                }
            }
            else
            {
                return "";
            }
        }
        private void BingFirstNodes(TreeNode nn)
        {
            string nodeValue = nn.Value;
            string id = "";
            string parentdept = "";
            if (nodeValue.IndexOf("~") > 0)
            {
                id = nodeValue.Split('~')[0].ToString().Trim();
                parentdept = nodeValue.Split('~')[1].ToString().Trim();
            }
            StrSQL = new StringBuilder();
            //StrSQL.AppendFormat("select departmentid,departmentname,(select departmentid from V_DEPARTMENT where departmentid=vt.parentid)  parentdept from V_DEPARTMENT  vt where parentid='{0}'", id);
            StrSQL.AppendFormat("select departmentid,departmentname,parentid as  parentdept from V_DEPARTMENT  vt where parentid='{0}'", id);
            DataTable dt = DataAccess.Instance("BizDB").ExecuteDataTable(StrSQL.ToString());
            if (dt.Rows.Count > 0)
            {
                if (nn.ChildNodes.Count > 0)
                {
                    nn.ChildNodes.Clear();
                }
                foreach (DataRow row in dt.Rows)
                {
                    TreeNode node = new TreeNode();
                    //string UserCount = GetUsers(row["departmentid"].ToString().Trim()).ToString();
                    node.Text = getDeptName(row["departmentname"].ToString().Trim());// +"[" + UserCount + "]";
                    node.Value = row["departmentid"].ToString().Trim() + "~" + row["parentdept"].ToString().Trim();
                    nn.ChildNodes.Add(node);
                }
                nn.Expand();
            }
        }
        private void BingDepartments()
        {
            StrSQL = new StringBuilder();
            StrSQL.AppendLine("select departmentid,departmentname,parentid  parentdept from V_DEPARTMENT  vt where parentid=0");
            //StrSQL.AppendLine("select id,name,parentdept from V_DEPARTMENT where parentid=0");
            DataTable dt = DataAccess.Instance("BizDB").ExecuteDataTable(StrSQL.ToString());
            int i = 0;
            foreach (DataRow row in dt.Rows)
            {
                TreeNode node = new TreeNode();
                //string UserCount = GetUsers(row["departmentid"].ToString().Trim()).ToString();
                node.Text = getDeptName(row["departmentname"].ToString().Trim());// +"[" + UserCount + "]";
                node.Value = row["departmentid"].ToString().Trim() + "~" + row["parentdept"].ToString().Trim();

                this.tvDept.Nodes.Add(node);
                if (i == 0)
                {
                    BingFirstNodes(node);
                }
                i++;
            }
        }

        protected void tvDept_SelectedNodeChanged(object sender, EventArgs e)
        {
            string nodeValue = this.tvDept.SelectedNode.Value;
            string id = "";
            string parentdept = "";
            if (nodeValue.IndexOf("~") > 0)
            {
                id = nodeValue.Split('~')[0].ToString().Trim();
                parentdept = nodeValue.Split('~')[1].ToString().Trim();
            }
            StrSQL = new StringBuilder();
            //StrSQL.AppendFormat("select departmentid,departmentname,(select departmentid from V_DEPARTMENT where departmentid=vt.parentid)  parentdept from V_DEPARTMENT  vt where parentid='{0}'", id);
            StrSQL.AppendFormat("select departmentid,departmentname,parentid as  parentdept from V_DEPARTMENT  vt where parentid='{0}'", id);
            DataTable dt = DataAccess.Instance("BizDB").ExecuteDataTable(StrSQL.ToString());
            if (dt.Rows.Count > 0)
            {
                if (tvDept.SelectedNode.ChildNodes.Count > 0)
                {
                    tvDept.SelectedNode.ChildNodes.Clear();
                }
                foreach (DataRow row in dt.Rows)
                {
                    TreeNode node = new TreeNode();
                    //string UserCount = GetUsers(row["departmentid"].ToString().Trim()).ToString();
                    node.Text = getDeptName(row["departmentname"].ToString().Trim());// +"[" + UserCount + "]";
                    node.Value = row["departmentid"].ToString().Trim() + "~" + row["parentdept"].ToString().Trim();
                    tvDept.SelectedNode.ChildNodes.Add(node);
                }
                tvDept.SelectedNode.Expand();
            }
        }

        protected void tvDept_TreeNodeCheckChanged(object sender, TreeNodeEventArgs e)
        {

        }

        protected void btn1_Click(object sender, EventArgs e)
        {

            rtnJson = "[";
            IterateTreeView(tvDept.Nodes);
            rtnJson = rtnJson.TrimEnd(new char[] { ',' });
            rtnJson += "]";
            Page.RegisterStartupScript("RtnVal", "<script>window.returnValue =" + rtnJson + ";window.close();</script>");
        }

        public void IterateTreeView(TreeNodeCollection tnc)
        {
            foreach (TreeNode tn in tnc)
            {
                if (tn.Checked)
                {
                    // strText+=""
                    rtnJson += "{'deptname':'" + tn.Text + "',";
                    rtnJson += "'deptid':'" + tn.Value.Split(new char[] { '~' })[0] + "',";
                    rtnJson += "'parentid':'" + tn.Value.Split(new char[] { '~' })[1] + "'},";
                }
                IterateTreeView(tn.ChildNodes);
            }
        }
    }
}